package cn.intotw.rdcj.core.config;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * @Descripition:
 * @Author: chenxiang
 * @Date: 2020年4月24日16:57:40
 */
@Component
public class GsonJsonView implements View {
    public static final String DEFAULT_CONTENT_TYPE = "application/json;charset=UTF-8";

    @Autowired
    Gson gson;

    @Override
    public String getContentType() {
        return DEFAULT_CONTENT_TYPE;
    }

    @Override
    public void render(Map<String, ?> map, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        //去掉bindresult
        map.entrySet().removeIf(stringEntry -> stringEntry.getValue() instanceof BindingResult);
        httpServletResponse.setHeader("Content-type", DEFAULT_CONTENT_TYPE);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.getWriter().print(gson.toJson(map));
    }
}
